package com.ipt.frm.pw.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ipt.frm.pw.Mensaje;
import com.ipt.frm.pw.Tipo;

public class CheckFilter extends FiltroMaestro {

	private FilterConfig filterConfig;

	private ArrayList<String> urlList;

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String url = request.getServletPath();
		boolean allowedRequest = false;
		RequestDispatcher dispatcher = null;
		System.out.println("url: " + url);
		if (urlList.contains(url)) {
			allowedRequest = true;
		}

		if (!allowedRequest) {
			HttpSession session = request.getSession();
			System.out.println("Username: " + session.getAttribute("username"));
			System.out.println("1IF");
			if (session != null) {
				if (session.getAttribute("username") == null) {

					request.setAttribute("MSG", new Mensaje(Tipo.INFO,
							"Debe logerase para poder usar la appWeb"));
					dispatcher = request.getRequestDispatcher("/login.jsp");
					dispatcher.forward(request, response);

					chain.doFilter(request, response);
				} else {
					chain.doFilter(request, response);
				}
			}

		} else {
			chain.doFilter(request, response);
		}

	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String urls = config.getInitParameter("avoid-urls");
		StringTokenizer token = new StringTokenizer(urls, ",");

		urlList = new ArrayList<String>();

		while (token.hasMoreTokens()) {
			urlList.add(token.nextToken());

		}
	}
}
